//
// Created by ole on 24-8-18.
//

#ifndef IPCSTRATEGYLOCALPROCESS_H
#define IPCSTRATEGYLOCALPROCESS_H
#include <mutex>
#include <queue>
#include <thread>
#include <unordered_map>
#include <unordered_set>

#include "IPCStrategy.h"


class IPCStrategyLocal final : public IPCStrategy {
public:
    ~IPCStrategyLocal() override = default;

    bool start() override;

    bool stop() override;

    void subscribe(const std::shared_ptr<Topic> &topic, const std::shared_ptr<MessageReceiver> &receiver) override;

    void unsubscribe(const std::shared_ptr<Topic> &topic, const std::shared_ptr<MessageReceiver> &receiver) override;

    void publishMessage(const std::shared_ptr<Message> &msg) override;

    void loopForever() override;

private:
    typedef std::unordered_set<std::shared_ptr<MessageReceiver> > ReceiverSet;

    void eventLoop();

    void handleEvent(const std::shared_ptr<Message> &msg);

    void dumpTopicReceivers() const;

    bool isStated = false;

    std::thread eventThread;

    std::mutex eventMutex;
    std::mutex memberMutex;
    std::mutex receiverMutex;

    std::priority_queue<std::shared_ptr<Message> > eventQueue;
    std::unordered_map<Topic, ReceiverSet> receiverSetMap;
    std::string TAG = "IPCStrategyLocal";
};

#endif //IPCSTRATEGYLOCALPROCESS_H
